<template>
  <div class="area-tree">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>区域树形管理</h2>
      <p>以树形结构展示和管理多级区域信息</p>
    </div>

    <div class="tree-container">
      <!-- 左侧树形结构 -->
      <div class="tree-panel">
        <div class="tree-header">
          <h3>区域树形结构</h3>
          <el-button type="primary" size="small" @click="handleAddRoot">
            <el-icon><Plus /></el-icon>
            添加根区域
          </el-button>
        </div>
        
        <el-scrollbar class="tree-content">
          <el-tree
            ref="treeRef"
            :data="treeData"
            :props="treeProps"
            node-key="id"
            :default-expand-all="false"
            :expand-on-click-node="false"
            :highlight-current="true"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <div class="node-content">
                  <el-icon class="node-icon">
                    <Location v-if="data.level === 1" />
                    <OfficeBuilding v-else-if="data.level === 2" />
                    <MapLocation v-else />
                  </el-icon>
                  <span class="node-label">{{ data.name }}</span>
                  <el-tag :type="getLevelTagType(data.level)" size="small">
                    {{ getLevelText(data.level) }}
                  </el-tag>
                </div>
                
                <div class="node-actions">
                  <el-button
                    type="primary"
                    size="small"
                    link
                    @click.stop="handleAddChild(data)"
                    v-if="data.level < 3"
                  >
                    <el-icon><Plus /></el-icon>
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    link
                    @click.stop="handleEdit(data)"
                  >
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    link
                    @click.stop="handleDelete(data)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>

      <!-- 右侧详情面板 -->
      <div class="detail-panel">
        <div class="detail-header">
          <h3>{{ selectedArea ? '区域详情' : '请选择区域' }}</h3>
          <el-button
            v-if="selectedArea"
            type="primary"
            @click="handleEdit(selectedArea)"
          >
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
        </div>
        
        <div class="detail-content" v-if="selectedArea">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="区域名称">
              {{ selectedArea.name }}
            </el-descriptions-item>
            <el-descriptions-item label="区域编码">
              {{ selectedArea.code }}
            </el-descriptions-item>
            <el-descriptions-item label="区域级别">
              <el-tag :type="getLevelTagType(selectedArea.level)">
                {{ getLevelText(selectedArea.level) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="上级区域">
              {{ selectedArea.parentName || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="排序">
              {{ selectedArea.sort }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="selectedArea.status === 1 ? 'success' : 'danger'">
                {{ selectedArea.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="备注">
              {{ selectedArea.remark || '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ selectedArea.createTime }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ selectedArea.updateTime }}
            </el-descriptions-item>
          </el-descriptions>
          
          <!-- 子区域列表 -->
          <div class="children-section" v-if="selectedArea.children?.length">
            <h4>下级区域</h4>
            <el-table :data="selectedArea.children" size="small">
              <el-table-column prop="name" label="区域名称" />
              <el-table-column prop="code" label="区域编码" />
              <el-table-column prop="level" label="级别">
                <template #default="{ row }">
                  <el-tag :type="getLevelTagType(row.level)" size="small">
                    {{ getLevelText(row.level) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
                    {{ row.status === 1 ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    size="small"
                    link
                    @click="handleNodeClick(row)"
                  >
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        
        <div class="empty-state" v-else>
          <el-empty description="请在左侧选择一个区域查看详情" />
        </div>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="上级区域" prop="parentId" v-if="formData.parentId">
          <el-input v-model="parentAreaName" disabled />
        </el-form-item>
        
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入区域名称" />
        </el-form-item>
        
        <el-form-item label="区域编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入区域编码" />
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import {
  Plus,
  Edit,
  Delete,
  Location,
  OfficeBuilding,
  MapLocation
} from '@element-plus/icons-vue'
import { areaApi } from '@/api/area'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const treeRef = ref<InstanceType<typeof ElTree>>()
const formRef = ref()

// 树形数据
const treeData = ref<any[]>([])
const selectedArea = ref<any>(null)

// 树形配置
const treeProps = {
  children: 'children',
  label: 'name'
}

// 表单数据
const formData = reactive({
  id: undefined as number | undefined,
  parentId: undefined as number | undefined,
  name: '',
  code: '',
  level: 1,
  sort: 0,
  status: 1,
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入区域名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入区域编码', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return formData.id ? '编辑区域' : '新增区域'
})

const parentAreaName = computed(() => {
  if (!formData.parentId) return ''
  const parent = findAreaById(treeData.value, formData.parentId)
  return parent ? parent.name : ''
})

// 方法
const loadTreeData = async () => {
  try {
    loading.value = true
    const response = await areaApi.getAreaTree()
    treeData.value = response.data
  } catch (error) {
    ElMessage.error('加载区域数据失败')
  } finally {
    loading.value = false
  }
}

const handleNodeClick = (data: any) => {
  selectedArea.value = data
  treeRef.value?.setCurrentKey(data.id)
}

const handleAddRoot = () => {
  resetForm()
  formData.level = 1
  dialogVisible.value = true
}

const handleAddChild = (parent: any) => {
  resetForm()
  formData.parentId = parent.id
  formData.level = parent.level + 1
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  Object.assign(formData, {
    id: row.id,
    parentId: row.parentId,
    name: row.name,
    code: row.code,
    level: row.level,
    sort: row.sort,
    status: row.status,
    remark: row.remark
  })
  dialogVisible.value = true
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除区域"${row.name}"吗？删除后不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await areaApi.deleteArea(row.id)
    ElMessage.success('删除成功')
    
    // 如果删除的是当前选中的区域，清空选中状态
    if (selectedArea.value?.id === row.id) {
      selectedArea.value = null
    }
    
    // 重新加载数据
    await loadTreeData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true
    
    if (formData.id) {
      await areaApi.updateArea(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      await areaApi.createArea(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    await loadTreeData()
    
    // 如果是更新操作，刷新选中的区域信息
    if (formData.id && selectedArea.value?.id === formData.id) {
      Object.assign(selectedArea.value, formData)
    }
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    parentId: undefined,
    name: '',
    code: '',
    level: 1,
    sort: 0,
    status: 1,
    remark: ''
  })
  formRef.value?.resetFields()
}

const getLevelTagType = (level: number) => {
  const types = ['', 'success', 'warning', 'info']
  return types[level] || 'info'
}

const getLevelText = (level: number) => {
  const texts = ['', '省/市', '市/区', '县/区']
  return texts[level] || '未知'
}

const findAreaById = (areas: any[], id: number): any => {
  for (const area of areas) {
    if (area.id === id) return area
    if (area.children?.length) {
      const found = findAreaById(area.children, id)
      if (found) return found
    }
  }
  return null
}

// 生命周期
onMounted(() => {
  loadTreeData()
})
</script>

<style lang="scss" scoped>
.area-tree {
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 20px;
      font-weight: 600;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }
  
  .tree-container {
    display: flex;
    gap: 20px;
    height: calc(100vh - 200px);
    
    .tree-panel {
      width: 400px;
      background: #fff;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      display: flex;
      flex-direction: column;
      
      .tree-header {
        padding: 16px;
        border-bottom: 1px solid #e4e7ed;
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
      
      .tree-content {
        flex: 1;
        padding: 16px;
        
        :deep(.el-tree) {
          .el-tree-node__content {
            height: 40px;
            
            &:hover {
              .node-actions {
                opacity: 1;
              }
            }
          }
          
          .tree-node {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            
            .node-content {
              display: flex;
              align-items: center;
              gap: 8px;
              flex: 1;
              
              .node-icon {
                font-size: 16px;
                color: #409eff;
              }
              
              .node-label {
                font-size: 14px;
                color: #303133;
              }
            }
            
            .node-actions {
              display: flex;
              gap: 4px;
              opacity: 0;
              transition: opacity 0.2s;
            }
          }
        }
      }
    }
    
    .detail-panel {
      flex: 1;
      background: #fff;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      display: flex;
      flex-direction: column;
      
      .detail-header {
        padding: 16px;
        border-bottom: 1px solid #e4e7ed;
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
      
      .detail-content {
        flex: 1;
        padding: 16px;
        overflow-y: auto;
        
        .children-section {
          margin-top: 24px;
          
          h4 {
            margin: 0 0 12px 0;
            font-size: 14px;
            font-weight: 600;
            color: #303133;
          }
        }
      }
      
      .empty-state {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

@media (max-width: 768px) {
  .area-tree {
    .tree-container {
      flex-direction: column;
      height: auto;
      
      .tree-panel {
        width: 100%;
        height: 400px;
      }
      
      .detail-panel {
        height: 400px;
      }
    }
  }
}
</style>